import * as express from "express";
import * as path from "path";
import {User} from '../models/User';
import {BaseController} from './BaseController';
import {AddGroupDto} from '../dtos/groups/AddGroupDto';
import {UpdateGroupDto} from '../dtos/groups/UpdateGroupDto';
import {GroupsService} from '../services/GroupsService';
import {Group} from '../models/Group';
export class GroupController extends BaseController
{
  groupsService:GroupsService;
  constructor(app:express.Application){
    super(app);
    var $this = this;
    app.post(this.domain+"/groups",(req,res)=>{
      $this.handerErr(req,res,()=>{
        $this.addGroup(req,res);
      },true);

    });
    app.put(this.domain+"/groups/:id",(req,res)=>{
      $this.handerErr(req,res,()=>{
        $this.updateGroup(req,res);
      },true);

    });
    app.get(this.domain+"/groups/:id",(req,res)=>{
      $this.handerErr(req,res,()=>{
        $this.getGroup(req,res);
      },true);

    });
    app.get(this.domain+"/groups/project/:id",(req,res)=>{
      $this.handerErr(req,res,()=>{
        $this.getGroups(req,res);
      },true);

    });
    app.delete(this.domain+"/groups/:id",(req,res)=>{
      $this.handerErr(req,res,()=>{
        $this.deleteGroup(req,res);
      },true);
    });
    this.groupsService = new GroupsService();
  }

  addGroup(req: express.Request, res: express.Response)
  {
    this.groupsService.addGroup(AddGroupDto.toGroup(req.body),(err,group:Group)=>{
      res.send(JSON.stringify(group));
    });
  }

  updateGroup(req: express.Request, res: express.Response)
  {
    //success
    var id = req.params.id;
    console.log(JSON.stringify(UpdateGroupDto.toGroup(id,req.body)));
    this.groupsService.updateGroup(UpdateGroupDto.toGroup(id,req.body),(err,group:Group)=>{
      console.log(JSON.stringify(group));
      res.send(JSON.stringify(group));
    });
  }

  getGroup(req: express.Request, res: express.Response)
  {
    var groupId:string = req.params.id;
    this.groupsService.getGroup(groupId,(err,group:Group)=>{
      res.send(JSON.stringify(group));
    });
  }

  getGroups(req: express.Request, res: express.Response)
  {
    var projectId:string = req.params.id;
    this.groupsService.getGroups(projectId,(err,groups:Group[])=>{
      res.send(JSON.stringify(groups));
    });
  }

  deleteGroup(req: express.Request, res: express.Response)
  {
    var groupId:string = req.params.id;
    this.groupsService.deleteGroup(groupId,(err,group:Group)=>{
      res.send(JSON.stringify(group));
    });
  }

}
